import { useContext, useEffect, useRef } from 'react';
import { MapContext } from '../../MapContext';
import {
  attachOldStation,
  detachOldStation,
  getOldStation,
} from '../../Mapless';
import type { Station } from '../../Mapless/index.d';

interface StationManaProps {
  id: string;
  stations: Station[];
}

export default function StationMana({ id, stations }: StationManaProps) {
  // TODO 如果useContext没有mapless则使用props中传入的
  const { mapless, isMapReady } = useContext(MapContext);
  const managerRef = useRef<ReturnType<typeof attachOldStation>>(null);

  // 初始化manager
  useEffect(() => {
    if (!mapless || !isMapReady) return;

    managerRef.current = attachOldStation(mapless, id);

    return () => {
      if (managerRef.current) {
        detachOldStation(mapless, id);
      }
    };
  }, [mapless, isMapReady, id]);

  // 更新stations
  useEffect(() => {
    if (!mapless || !isMapReady || !managerRef.current) return;

    const manager = getOldStation(mapless, id);
    if (manager) {
      manager.drawStations(stations || []);
    }
  }, [mapless, isMapReady, id, stations]);

  return null;
}
